import React, { useState, useEffect } from 'react';
import { productApi } from '../services/api';

interface Product {
  id: number;
  name: string;
  category: string;
  price: number;
  originalPrice: number;
  stock: number;
  status: 'active' | 'inactive';
  isHot: boolean;
  isRecommend: boolean;
  createTime: string;
  image: string;
}

const ProductList: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [formData, setFormData] = useState({
    name: '',
    category: '',
    price: '',
    originalPrice: '',
    stock: '',
    status: 'active' as 'active' | 'inactive',
    isHot: false,
    isRecommend: false,
    image: ''
  });

  const [categories, setCategories] = useState<string[]>([]);

  useEffect(() => {
    // 获取商品分类
    const fetchCategories = async () => {
      try {
        const response: any = await productApi.getCategories();
        if (response.isSuccess && response.data) {
          setCategories(response.data);
        }
      } catch (error) {
        console.error('获取分类失败:', error);
      }
    };
    fetchCategories();
  }, []);

  useEffect(() => {
    // 调用API获取商品列表
    const fetchProducts = async () => {
      try {
        const response: any = await productApi.getProducts(currentPage, pageSize, selectedCategory);
        if (response.isSuccess && response.data) {
          setProducts(response.data);
          setTotal(response.total || 0);
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        alert('获取商品列表失败');
      }
    };
    fetchProducts();
  }, [currentPage, pageSize, selectedCategory]);

  const handleAdd = () => {
    setEditingProduct(null);
    setFormData({
      name: '',
      category: '',
      price: '',
      originalPrice: '',
      stock: '',
      status: 'active',
      isHot: false,
      isRecommend: false,
      image: ''
    });
    setShowModal(true);
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    setFormData({
      name: product.name,
      category: product.category,
      price: product.price.toString(),
      originalPrice: product.originalPrice.toString(),
      stock: product.stock.toString(),
      status: product.status,
      isHot: product.isHot,
      isRecommend: product.isRecommend,
      image: product.image
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      try {
        await productApi.deleteProduct(id);
        // 重新获取商品列表
        const response: any = await productApi.getProducts(currentPage, pageSize, selectedCategory);
        if (response.isSuccess && response.data) {
          setProducts(response.data);
          setTotal(response.total || 0);
        }
        alert('删除成功');
      } catch (error) {
        console.error('删除商品失败:', error);
        alert('删除商品失败');
      }
    }
  };

  const handleSubmit = async () => {
    if (!formData.name || !formData.category || !formData.price || !formData.stock) {
      alert('请填写完整信息');
      return;
    }

    try {
      const submitData = {
        name: formData.name,
        category: formData.category,
        price: parseFloat(formData.price),
        originalPrice: parseFloat(formData.originalPrice),
        stock: parseInt(formData.stock),
        status: formData.status,
        isHot: formData.isHot,
        isRecommend: formData.isRecommend,
        image: formData.image
      };

      if (editingProduct) {
        // 编辑商品
        await productApi.updateProduct(editingProduct.id, submitData);
        alert('更新成功');
      } else {
        // 新增商品
        await productApi.createProduct(submitData);
        alert('创建成功');
      }
      
      // 重新获取商品列表
      const response: any = await productApi.getProducts(currentPage, pageSize, selectedCategory);
      if (response.isSuccess && response.data) {
        setProducts(response.data);
        setTotal(response.total || 0);
      }
      setShowModal(false);
    } catch (error) {
      console.error('操作失败:', error);
      alert('操作失败');
    }
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div style={{ padding: 24 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2>商品管理</h2>
        <button 
          onClick={handleAdd}
          style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer' }}
        >
          新增商品
        </button>
      </div>

      {/* 筛选区域 */}
      <div style={{ marginBottom: 16, padding: '16px', background: 'white', borderRadius: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <span>分类筛选：</span>
          <select
            value={selectedCategory}
            onChange={(e) => setSelectedCategory(e.target.value)}
            style={{ padding: '8px 12px', border: '1px solid #d9d9d9', borderRadius: 4 }}
          >
            <option value="all">全部分类</option>
            {categories.map(category => (
              <option key={category} value={category}>{category}</option>
            ))}
          </select>
        </div>
      </div>

      {/* 商品表格 */}
      <div style={{ background: 'white', borderRadius: 8, overflow: 'hidden', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: '#fafafa' }}>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>商品图片</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>商品名称</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>分类</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>价格</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>库存</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>状态</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>标签</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>创建时间</th>
              <th style={{ padding: 12, textAlign: 'left', borderBottom: '1px solid #f0f0f0' }}>操作</th>
            </tr>
          </thead>
          <tbody>
            {products.map(product => (
              <tr key={product.id} style={{ borderBottom: '1px solid #f0f0f0' }}>
                <td style={{ padding: 12 }}>
                  <img 
                    src={product.image} 
                    alt={product.name}
                    style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }}
                  />
                </td>
                <td style={{ padding: 12 }}>{product.name}</td>
                <td style={{ padding: 12 }}>{product.category}</td>
                <td style={{ padding: 12 }}>
                  <div style={{ color: '#ff4d4f', fontWeight: 'bold' }}>¥{product.price}</div>
                  <div style={{ color: '#999', textDecoration: 'line-through', fontSize: 12 }}>¥{product.originalPrice}</div>
                </td>
                <td style={{ padding: 12 }}>{product.stock}</td>
                <td style={{ padding: 12 }}>
                  <span style={{ 
                    padding: '4px 8px', 
                    borderRadius: 4, 
                    fontSize: 12,
                    background: product.status === 'active' ? '#f6ffed' : '#fff2e8',
                    color: product.status === 'active' ? '#52c41a' : '#fa8c16'
                  }}>
                    {product.status === 'active' ? '上架' : '下架'}
                  </span>
                </td>
                <td style={{ padding: 12 }}>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    {product.isHot && (
                      <span style={{ padding: '2px 6px', background: '#fff2e8', color: '#fa8c16', borderRadius: 2, fontSize: 10 }}>
                        热门
                      </span>
                    )}
                    {product.isRecommend && (
                      <span style={{ padding: '2px 6px', background: '#f0f5ff', color: '#1890ff', borderRadius: 2, fontSize: 10 }}>
                        推荐
                      </span>
                    )}
                  </div>
                </td>
                <td style={{ padding: 12 }}>{product.createTime}</td>
                <td style={{ padding: 12 }}>
                  <button 
                    onClick={() => handleEdit(product)}
                    style={{ marginRight: 8, padding: '4px 8px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                  >
                    编辑
                  </button>
                  <button 
                    onClick={() => handleDelete(product.id)}
                    style={{ padding: '4px 8px', background: '#ff4d4f', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer', fontSize: 12 }}
                  >
                    删除
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button 
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === 1 ? '#f5f5f5' : '#1890ff', 
              color: currentPage === 1 ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === 1 ? 'not-allowed' : 'pointer' 
            }}
          >
            上一页
          </button>
          <span style={{ padding: '8px 12px' }}>
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          <button 
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages}
            style={{ 
              padding: '8px 12px', 
              background: currentPage === totalPages ? '#f5f5f5' : '#1890ff', 
              color: currentPage === totalPages ? '#ccc' : 'white', 
              border: 'none', 
              borderRadius: 4, 
              cursor: currentPage === totalPages ? 'not-allowed' : 'pointer' 
            }}
          >
            下一页
          </button>
        </div>
      </div>

      {/* 新增/编辑模态框 */}
      {showModal && (
        <div style={{
          position: 'fixed',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          background: 'rgba(0,0,0,0.5)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          zIndex: 1000
        }}>
          <div style={{
            background: 'white',
            padding: 24,
            borderRadius: 8,
            width: 500,
            maxWidth: '90vw',
            maxHeight: '90vh',
            overflowY: 'auto'
          }}>
            <h3 style={{ marginTop: 0, marginBottom: 24 }}>
              {editingProduct ? '编辑商品' : '新增商品'}
            </h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>商品名称：</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({...formData, name: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                  placeholder="请输入商品名称"
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>分类：</label>
                <select
                  value={formData.category}
                  onChange={(e) => setFormData({...formData, category: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                >
                  <option value="">请选择分类</option>
                  {categories.map(category => (
                    <option key={category} value={category}>{category}</option>
                  ))}
                </select>
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>售价：</label>
                <input
                  type="number"
                  value={formData.price}
                  onChange={(e) => setFormData({...formData, price: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                  placeholder="请输入售价"
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>原价：</label>
                <input
                  type="number"
                  value={formData.originalPrice}
                  onChange={(e) => setFormData({...formData, originalPrice: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                  placeholder="请输入原价"
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>库存：</label>
                <input
                  type="number"
                  value={formData.stock}
                  onChange={(e) => setFormData({...formData, stock: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                  placeholder="请输入库存"
                />
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>状态：</label>
                <select
                  value={formData.status}
                  onChange={(e) => setFormData({...formData, status: e.target.value as 'active' | 'inactive'})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                >
                  <option value="active">上架</option>
                  <option value="inactive">下架</option>
                </select>
              </div>
              <div>
                <label style={{ display: 'block', marginBottom: 8 }}>商品图片：</label>
                <input
                  type="text"
                  value={formData.image}
                  onChange={(e) => setFormData({...formData, image: e.target.value})}
                  style={{ width: '100%', padding: 8, border: '1px solid #d9d9d9', borderRadius: 4 }}
                  placeholder="请输入图片URL"
                />
              </div>
            </div>
            <div style={{ marginTop: 16 }}>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                <input
                  type="checkbox"
                  checked={formData.isHot}
                  onChange={(e) => setFormData({...formData, isHot: e.target.checked})}
                />
                热门商品
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <input
                  type="checkbox"
                  checked={formData.isRecommend}
                  onChange={(e) => setFormData({...formData, isRecommend: e.target.checked})}
                />
                推荐商品
              </label>
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', marginTop: 24 }}>
              <button
                onClick={() => setShowModal(false)}
                style={{ padding: '8px 16px', background: '#f0f0f0', border: '1px solid #d9d9d9', borderRadius: 4, cursor: 'pointer' }}
              >
                取消
              </button>
              <button
                onClick={handleSubmit}
                style={{ padding: '8px 16px', background: '#1890ff', color: 'white', border: 'none', borderRadius: 4, cursor: 'pointer' }}
              >
                确定
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProductList; 